//
//  ChangePhoneViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/9.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "ChangePhoneViewController.h"
#import "ChangePWItem.h"

@interface ChangePhoneViewController ()

@property (nonatomic, strong) ChangePWItem *item1;
@property (nonatomic, strong) ChangePWItem *item2;
@property (nonatomic, strong) ChangePWItem *item3;
@property (nonatomic, strong) UIButton *timeBtn;

@end

@implementation ChangePhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorFromRGB(0xf5f5f5);
    [self loadBaseTitleLable:@"换绑手机"];
    
    self.rightBtn.hidden = NO;
    [self.rightBtn setTitle:@"  保存  " forState:(UIControlStateNormal)];
    [self.rightBtn addTarget:self action:@selector(actionSave) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self setUpUI];
}
- (void)setUpUI
{
    ChangePWItem *item1 = [[ChangePWItem alloc] init];
    item1.textField.placeholder = @"请输入新的手机号";
    [self.view addSubview:item1];
    [item1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(rateWidth(660), rateHeight(90)));
        make.top.equalTo(self.view).offset(rateHeight(20)+SafeAreaTopHeight);
        make.centerX.equalTo(self.view);
    }];
    self.item1 = item1;
    
    ChangePWItem *item3 = [[ChangePWItem alloc] init];
    item3.textField.placeholder = @"请输入安全密码";
    item3.textField.secureTextEntry = YES;
    [self.view addSubview:item3];
    [item3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(rateWidth(660), rateHeight(90)));
        make.top.equalTo(item1.mas_bottom).offset(rateHeight(20));
        make.centerX.equalTo(self.view);
    }];
    self.item3 = item3;
    
    ChangePWItem *item2 = [[ChangePWItem alloc] init];
    item2.textField.placeholder = @"请输入验证码";
    [self.view addSubview:item2];
    [item2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(rateWidth(660), rateHeight(90)));
        make.top.equalTo(item3.mas_bottom).offset(rateHeight(20));
        make.centerX.equalTo(self.view);
    }];
    self.item2 = item2;
    UIButton *btn = [UIButton buttonWithTitle:@"发送验证码" fontSize:13 titleColor:UIColorWhite background:navBarColor cornerRadius:0];
    [item2 addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(rateWidth(210), rateHeight(90)));
        make.right.equalTo(item2);
        make.centerY.equalTo(item2);
    }];
    self.timeBtn = btn;
    [self.timeBtn addTarget:self action:@selector(getPhoneCode) forControlEvents:(UIControlEventTouchUpInside)];
    
    
}
#pragma mark - 保存
- (void)actionSave
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/member/safe.ashx?action=editmobileoremail&chkType=106&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"chkData1":self.item1.textField.text,@"chkData2":self.item2.textField.text,@"chkData3":self.item3.textField.text} success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (responseObject) {
            if ([responseObject[@"status"] intValue] == 1) {
                if ([responseObject[@"chkType"] intValue] == 0) {
                    [MBProgressHUD showSuccess:@"手机号码绑定成功"];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
            } else {
                [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
            }
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
#pragma mark - 获取验证码
- (void)getPhoneCode
{
    if (self.item1.textField.text.length == 11) {
        [self getCodeRequest]; // 注册获取验证码
    } else {
        [TFHUD addRemindHUD:self.view message:@"请输入正确的手机号"];
    }
}
- (void)getCodeRequest
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/member/safe.ashx?action=editmobileoremail&chkType=102&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"chkData1":self.item1.textField.text,@"chkData2":self.item3.textField.text} success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (responseObject) {
            if ([responseObject[@"status"] intValue] == 1) {
                if ([responseObject[@"chkType"] intValue] == 0) {
                    [TFHUD addRemindHUD:self.view message:@"发送成功，请查看您的手机短信获取校验码"];
                    [self startTime];
                }
            } else {
                [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
            }
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
-(void)startTime
{
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置（倒计时结束后调用）
                [self.timeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
                //设置可点击
                self.timeBtn.userInteractionEnabled = YES;
                
            });
        }else{
            //            int minutes = timeout / 60;    //这里注释掉了，这个是用来测试多于60秒时计算分钟的。
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //                NSLog(@"____%@",strTime);
                [self.timeBtn setTitle:[NSString stringWithFormat:@"%@s",strTime] forState:(UIControlStateNormal)];
                //设置可点击
                self.timeBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
